/*
 *  AGraphicEffectAttr.cpp
 *  libavid
 *
 *  Created by Peter on 25.02.12.
 *  Copyright 2012 __MyCompanyName__. All rights reserved.
 *
 */

#include "AGraphicEffectAttr.h"
#include "AStream.h"
#include <iomanip>

A_IMPLEMENT_CLASS( 'GRFX', AGraphicEffectAttr, AObject );

AGraphicEffectAttr::AGraphicEffectAttr()
	: _pictSize( 0 )
    , _pictData( nullptr )
{
}

void AGraphicEffectAttr::readFromStream( AStream& str, const AObjDoc& objd )
{
	UInt8 tagMark, version;
	str.readPod( tagMark );
	str.readPod( version );
	TR_ASSERT( tagMark == 0x02 );
	TR_ASSERT( version == 0x01 );
	
	str.readPod( _pictSize );
	
	TR_ASSERT( _pictSize >= 0 );
	
	if( _pictSize == 0 ) {
		_pictData = nullptr;  // TODO: Make sure we don't leak anything
	} else {
		_pictData = new UInt8[ _pictSize ];
		str.readBuffer( _pictData, _pictSize );
	}
	
	str.readPod( tagMark );
	TR_ASSERT( tagMark == 0x03 );
}

// Not perfect, but works well enough for now.
static void writeHexBuffer( std::ostream& str, int len, UInt8* buffer )
{
	if( !len )
		return;
	
	// Prevent buffer underruns
	TR_ASSERT( len > 0 );
	
	// Save the state of the stream.
	// This code is from Tropic::StdStreamStateGuard, which is of course a much
	// more elegant (and exception safe) solution, but not worth it here since
	// the manual code is reasonably simple.
	std::ios::fmtflags flags = str.flags();
	
	str 
	// << std::uppercase   // uppercase digits (disadvantage: also affects the '0x')
	<< std::setfill('0')  // fill with leading zeroes if necessary
	<< std::hex;           // display as hex
  //<< std::showbase;     // prefix with '0x'
	
	for( int i = 0; i < len; ++i )
	{
		str << std::setw( 2 )     // two digits per value
			<< static_cast< unsigned int >( buffer[ i ] );
		
		// Put a space inbetween each hex value
		if( i != len )
			str << " ";
	}
	
	// Reconstruct our stream
	str.flags( flags );
}

void AGraphicEffectAttr::dump( std::ostream& str ) const
{
	str << "AGraphicEffectAttr {" << std::endl;
	
	str << "\t_pictSize: " << _pictSize << std::endl;
	str << "\t_pictData: ";
	writeHexBuffer( str, _pictSize, _pictData );
	str << std::endl;
	
	str << "}" << std::endl;
}